package cn.zqh.commodity.service.impl;

import cn.zqh.bean.api.CommonResult;
import cn.zqh.bean.api.ResultCode;
import cn.zqh.bean.bo.*;
import cn.zqh.commodity.client.BrandClient;
import cn.zqh.commodity.client.StoreClient;
import cn.zqh.commodity.config.BSException;
import cn.zqh.commodity.holder.LoginUserHolder;
import cn.zqh.commodity.mapper.CommodityMapper;
import cn.zqh.commodity.service.CommodityService;
import cn.zqh.commodity.utils.EsCommodityUtils;
import cn.zqh.uuid.utils.SnowflakeId;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zqh
 * @since 2022-12-24
 */
@Service
public class CommodityServiceImpl extends ServiceImpl<CommodityMapper, Commodity> implements CommodityService {

    @Resource
    private CommodityMapper commodityMapper;

    @Autowired
    private LoginUserHolder loginUserHolder;
    @Autowired
    private StoreClient storeClient;
    @Autowired
    private EsCommodityUtils esCommodityUtils;
    @Autowired
    private BrandClient brandClient;

    @Autowired
    private RestTemplate restTemplate;


    /**
      * @Author: zqh
      * @Date:
      * @Description: 添加一个新的商品
    */
    @Override
    public CommonResult addANewCommodity(@RequestBody Pfoods pfoods)throws IOException {
        UserDTO currentUser = loginUserHolder.getCurrentUser();
        if (currentUser == null) {
            throw new BSException(ResultCode.UNAUTHORIZED.getCode(),ResultCode.UNAUTHORIZED.getMessage());
        }
        //获取当前操作用户的信息，通过用户信息拿到店铺信息
        //Store commonResult = storeClient.QueryTheStoresUnderTheCompanyThroughTheUserPrimaryKey(currentUser.getId());
        CommonResult res = restTemplate.getForObject("http://127.0.0.1:9601/store/getStoreByUserId?uid=" + currentUser.getId(), CommonResult.class);
        String s = JSON.toJSONString(res.getData());
        Store store = JSON.parseObject(s, Store.class);
        if (res == null){
            throw new BSException(ResultCode.VALIDATE_FAILED.getCode(),ResultCode.VALIDATE_FAILED.getMessage());
        }
        Commodity commodity = new Commodity();
        commodity
                //商品头像自己上传
                .setAvatar(pfoods.getAvatar())
                //主键id雪花算法自动生成
                .setCommodityId("commodity"+SnowflakeId.nextId())
                //商品名字，自己上传
                .setCommodityName(pfoods.getCommodityName())
                //商品简介，自己上传
                .setIntro(pfoods.getIntro())
                //逻辑删除
                .setIsDelete(0)
                //商品库存
                .setNumber(0)
                //商品定价，商家设置
                .setPrice(pfoods.getPrice())
                //售卖数量
                .setSalesVolume(0)
                //商品所属商店
                .setStoreId(String.valueOf(store.getStoreId()))
                //商品功效
                .setStyle(pfoods.getStyle())
                //所属品牌id
                .setBrandId(pfoods.getBrandId());


        boolean b = esCommodityUtils.addOne(commodity);
        if (b != true){
            throw new BSException(ResultCode.THEESDATABASEALREADYEXISTS.getCode(),ResultCode.THEESDATABASEALREADYEXISTS.getMessage());
        }
        int i = commodityMapper.insert(commodity);
        if(i != 1){
            throw new BSException(ResultCode.FAILED.getCode(),ResultCode.FAILED.getMessage());
        }
        System.out.println("操作成功");
        return CommonResult.success(ResultCode.SUCCESS);
    }

    /**
      * @Author: zqh
      * @Date:
      * @Description: 查询所有商品
    */
    @Override
    @Transactional(readOnly = true)
    public CommonResult getAll() {
        List<Commodity> commodities = commodityMapper.selectList(null);
        return CommonResult.success(commodities);
    }

    /**
      * @Author: zqh
      * @Date:
      * @Description: 根据商品id删除商品
    */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public CommonResult delACommodityById(String id) throws IOException{
        Commodity commodity = commodityMapper.selectOne(new QueryWrapper<Commodity>().eq("Commodity_id", id));
        if (commodity == null) {
            throw new BSException(ResultCode.VALIDATE_FAILED.getCode(),ResultCode.VALIDATE_FAILED.getMessage());
        }
        boolean b = esCommodityUtils.deleteOne(commodity.getCommodityId());
        if (b != true){
            throw new BSException(ResultCode.FAILED.getCode(),ResultCode.FAILED.getMessage());
        }
        int i = commodityMapper.deleteById(commodity.getCommodityId());
        if (i != 1){
            throw new BSException(ResultCode.FAILED.getCode(),ResultCode.FAILED.getMessage());
        }
        return CommonResult.success(ResultCode.SUCCESS);
    }

    /**
      * @Author: zqh
      * @Date:
      * @Description: 店主修改商品信息
    */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public CommonResult StoreOwnerModifiesProductInformation(UserChangeCommodity userChangeCommodity) throws IOException{
        Commodity commodity = commodityMapper.selectOne(new QueryWrapper<Commodity>().eq("Commodity_id", userChangeCommodity.getCommodityId()));
        if (commodity == null) {
            throw new BSException(ResultCode.VALIDATE_FAILED.getCode(),ResultCode.VALIDATE_FAILED.getMessage());
        }
        commodity.setCommodityName(userChangeCommodity.getCommodityName())
                .setAvatar(userChangeCommodity.getAvatar())
                .setIntro(userChangeCommodity.getIntro())
                .setStyle(userChangeCommodity.getStyle())
                .setPrice(userChangeCommodity.getPrice())
                .setBrandId(userChangeCommodity.getBrandId())
                .setNumber(userChangeCommodity.getNumber());
        int i = commodityMapper.updateById(commodity);
        if (i != 1){
            throw new BSException(ResultCode.FAILED.getCode(), ResultCode.FAILED.getMessage());
        }else {
            boolean b = esCommodityUtils.deleteOne(commodity.getCommodityId());
            if (b != true) {
                throw new BSException(ResultCode.FAILED.getCode(), ResultCode.FAILED.getMessage());
            }
            boolean c = esCommodityUtils.addOne(commodity);
            if (c != true){
                throw new BSException(ResultCode.FAILED.getCode(),ResultCode.FAILED.getMessage());
            }
            return CommonResult.success(ResultCode.SUCCESS);
        }
    }
    
    /**
      * @Author: zqh
      * @Date: 
      * @Description: 管理员修改商品信息
    */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public CommonResult ModifyTheProductInformationBasedOnTheAdministrator(AdminChangeCommodity adminChangeCommodity) throws IOException{
        Commodity commodity = commodityMapper.selectOne(new QueryWrapper<Commodity>().eq("Commodity_id", adminChangeCommodity.getCommodityId()));
        if (commodity == null) {

            throw new BSException(( ResultCode.VALIDATE_FAILED.getCode()),ResultCode.VALIDATE_FAILED.getMessage());
        }
        commodity
                //修改商品名
                .setCommodityName(adminChangeCommodity.getCommodityName())
                //修改商品图片
                .setAvatar(adminChangeCommodity.getAvatar())
                //修改商品简介
                .setIntro(adminChangeCommodity.getIntro())
                //修改商品所属风格
                .setStyle(adminChangeCommodity.getStyle())
                //修改价格
                .setPrice(adminChangeCommodity.getPrice())
                //修改库存量
                .setNumber(adminChangeCommodity.getNumber())
                //更改商品的品牌
                .setBrandId(adminChangeCommodity.getBrandId())
                //修改销售量
                .setSalesVolume(adminChangeCommodity.getSalesVolume());
        int i = commodityMapper.updateById(commodity);
        if (i != 1){
            throw new BSException(ResultCode.FAILED.getCode(),ResultCode.FAILED.getMessage());
        } else {
            boolean b = esCommodityUtils.deleteOne(commodity.getCommodityId());
            System.out.println(b+"vakdf");
            if (b != true) {
                throw new BSException(ResultCode.FAILED.getCode(), ResultCode.FAILED.getMessage());
            }
            boolean c = esCommodityUtils.addOne(commodity);
            System.out.println(c+"dfsdf");
            if (c != true){
                throw new BSException(ResultCode.FAILED.getCode(),ResultCode.FAILED.getMessage());
            }
            return CommonResult.success(ResultCode.SUCCESS);
        }

    }


    /**
      * @Author: zqh
      * @Date:
      * @Description: 创建commodity的es数据库
    */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public CommonResult CreateEsDataBaseOfCommodity() throws IOException{
        boolean b = esCommodityUtils.CreateIndex();
        if (b != true){
            throw new BSException(ResultCode.THEESDATABASEALREADYEXISTS.getCode(),ResultCode.THEESDATABASEALREADYEXISTS.getMessage());
        }
        return CommonResult.success(ResultCode.SUCCESS);
    }


    /**
      * @Author: zqh
      * @Date:
      * @Description: 删除commodity的es数据库
    */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public CommonResult DelEsDataBaseOfCommodity() throws IOException{
        boolean b = esCommodityUtils.DeleteIndex();
        if (b != true){
            throw new BSException(ResultCode.THEESDATABASEALREADYEXISTS.getCode(),ResultCode.THEESDATABASEALREADYEXISTS.getMessage());
        }
        return CommonResult.success(ResultCode.SUCCESS);
    }

    /**
      * @Author: zqh
      * @Date:
      * @Description: 查看commodity的es数据库是否存在
    */
    @Override
    @Transactional(readOnly = true)
    public CommonResult DetermineWhetherTheEsCommunityExists() throws IOException{
        boolean b = esCommodityUtils.GetIndex();
        if (b != true){
            throw new BSException(ResultCode.THEESDATABASEALREADYEXISTS.getCode(),ResultCode.THEESDATABASEALREADYEXISTS.getMessage());
        }
        return CommonResult.success(ResultCode.SUCCESS);
    }

    /**
      * @Author: zqh
      * @Date:
      * @Description: 把数据库中所有商品数据上传到es数据库
    */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public CommonResult UploadAllDataInTheDatabaseToTheEsDatabase()throws IOException {
        List<Commodity> commodities = commodityMapper.selectList(new QueryWrapper<Commodity>().eq("Is_delete",0));
        boolean b = esCommodityUtils.addAll(commodities);
        if (b != true){
            throw new BSException(ResultCode.THEESDATABASEALREADYEXISTS.getCode(),ResultCode.THEESDATABASEALREADYEXISTS.getMessage());
        }
        return CommonResult.success(ResultCode.SUCCESS);
    }

    /**
      * @Author: zqh
      * @Date:
      * @Description: 搜索时给用户提示
    */
    @Override
    @Transactional(readOnly = true)
    public CommonResult searchEngines(String t) throws IOException {
        List<String> autocompletionList = esCommodityUtils.getAutocompletionList(t);
        return CommonResult.success(autocompletionList);
    }

    /**
      * @Author: zqh
      * @Date:
      * @Description: 多条件复合查询
    */
    @Override
    @Transactional(readOnly = true)
    public CommonResult CompoundQuery(SearchBean searchBean)throws IOException {
        HashMap<String, Object> hashMap = esCommodityUtils.multiConditionalCompoundQuery(searchBean);
//        long title = (long) hashMap.get("title");
//        List<EsCommodity> escommoditys = (List<EsCommodity>) hashMap.get("escommoditys");
//        for (EsCommodity commodity : escommoditys) {
//            commodity.setIsDelete(0);
//        }
        return CommonResult.success(hashMap);
    }
    
    
    /**
      * @Author: zqh
      * @Date: 
      * @Description: 根据id获取商品信息
    */
    @Override
    @Transactional(readOnly = true)
    public CommonResult getCommodityById(String id) throws IOException {
        EsCommodity commodity = esCommodityUtils.getEsCommodityById(id);
        return CommonResult.success(commodity);
    }

    /**
      * @Author: zqh
      * @Date:
      * @Description: 获取商品信息
    */
    @Override
    @Transactional(readOnly = true)
    public CommonResult gCommodity(String id) {
        Commodity commodity = commodityMapper.selectById(id);
        return CommonResult.success(commodity);
    }

    /**
      * @Author: zqh
      * @Date:
      * @Description: 获取所有商品的数量
    */
    @Override
    @Transactional(readOnly = true)
    public CommonResult getAllCommodityNumbers(Integer del) {
        Integer coNumber = commodityMapper.getCoNumber(del);
        return CommonResult.success(coNumber);
    }

    /**
      * @Author: zqh
      * @Date:
      * @Description: 查询被删除了的所有商品
    */
    @Override
    @Transactional(readOnly = true)
    public CommonResult getDelCommoditys(Integer page,Integer size) {
        List<Commodity> commodities = commodityMapper.getDelComs((page-1)*size,size);
        return CommonResult.success(commodities);
    }

    /**
      * @Author: zqh
      * @Date:
      * @Description: 把删除的商品取消删除
    */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public CommonResult cancelDeletionOfDeletedGoods(String id) throws IOException {
        commodityMapper.updateCommodityIsdel(id);
        Commodity commodity = commodityMapper.selectById(id);
        boolean b = esCommodityUtils.updateOne(commodity);
        if (b != true){
            throw new BSException(ResultCode.FAILED.getCode(),ResultCode.FAILED.getMessage());
        }
        return CommonResult.success(ResultCode.SUCCESS);
    }


    @Override
    public CommonResult changeItemInventory(String commodityId, Integer number) throws IOException{
        Commodity commodity = commodityMapper.selectById(commodityId);
        commodity.setNumber(commodity.getNumber() - number);
        boolean b = esCommodityUtils.deleteOne(commodityId);
        if (b != true){
            return CommonResult.failed();
        }
        boolean b1 = esCommodityUtils.updateOne(commodity);
        if (b1 != true){
            return CommonResult.failed();
        }
        int i = commodityMapper.updateById(commodity);
        if (i != 1){
            return CommonResult.failed();
        }
        return CommonResult.success(ResultCode.SUCCESS);
    }


}
